// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

exports.main = async (event, context) => {
  const db = cloud.database()

  // 随机获取4条POI数据并添加type
  const getPoisData = async () => {
    try {
      const res = await db.collection('Pois')
        .aggregate()
        .sample({ size: 4 })
        .end()
      return res.list.map(item => ({ ...item, type: 'pois',chtype:'大坪故居' }))
    } catch (e) {
      console.error('POI数据获取失败:', e)
      return []
    }
  }

  // 随机获取4条生态数据并添加type
  const getEcologyData = async () => {
    try {
      const res = await db.collection('EcologyList')
        .aggregate()
        .sample({ size: 4 })
        .end()
      return res.list.map(item => ({ ...item, type: 'ecology',chtype:'大坪生态' }))
    } catch (e) {
      console.error('生态数据获取失败:', e)
      return []
    }
  }

  // 获取基地主场地data数据（优化版）
  const getBaseData = async () => {
    try {
      // 获取所有基地文档的data字段
      const { data: venues } = await db.collection('Venues')
        .field({
          _id: false,
          data: true
        })
        .get()

      // 合并并过滤有效数据
      const allData = venues
        .filter(v => v.data && v.data.length)
        .flatMap(v => v.data)

      // 随机采样算法
      const sampleSize = 4
      if (allData.length <= sampleSize) return allData
      
      return allData
        .map(a => ({ ...a, sort: Math.random() }))
        .sort((a, b) => a.sort - b.sort)
        .slice(0, sampleSize)
        .map(({ sort, ...item }) => ({
          ...item,
          type: 'venue',
          chtype:'大坪基地'
        }))

    } catch (e) {
      console.error('基地数据获取失败：', e)
      return []
    }
  }

  // 美食数据
  const getFoodData = async () => {
    try {
      const res = await db.collection('FoodList') // 假设存在美食集合
        .aggregate()
        .sample({ size: 4 })
        .end()
      return res.list.map(item => ({ 
        ...item, 
        _id:item._id,
        type: 'food',
        chtype: '大坪美食',
        // food_image: item.image || '/images/default_food.jpg', // 默认图
        food_image: item.food_image,
        food_name: item.food_name || '神秘美食'
      }))
    } catch (e) {
      console.error('美食数据获取失败:', e)
      return []
    }
  }

  // 传记数据
  const getStoryData = async () => {
    try {
      const res = await db.collection('StoryList')
        .aggregate()
        .sample({ size: 4 })
        .end()
      return res.list.map(item => ({ 
        ...item, 
        _id:item._id,
        type: 'story',
        chtype: '大坪传记',
        // food_image: item.image || '/images/default_food.jpg', // 默认图
        detail: item.detail,
        name: item.title 
      }))
    } catch (e) {
      console.error('传记数据获取失败:', e)
      return []
    }
  }

  try {
    // 并行获取所有数据
    const [pois, ecology, bases,foods,story] = await Promise.all([
      getPoisData(),
      getEcologyData(),
      getBaseData(),
      getFoodData(), 
      getStoryData()
    ])

    // 合并所有结果
    const combinedData = [...pois, ...ecology, ...bases,...foods,...story]

    return {
      code: 200,
      message: 'success',
      data: combinedData
    }
  } catch (err) {
    console.error('云函数执行失败:', err)
    return {
      code: 500,
      message: '服务器异常',
      data: null
    }
  }
}